﻿using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEditor;
using UnityEngine;
using UnityEngine.Serialization;
using UnityEngine.UIElements;
using Random = UnityEngine.Random;

// ReSharper disable CheckNamespace

public class ChessManager :  SingletonMono<ChessManager>
{
    
    private Dictionary<Vector2Int, Chess> chessDict = new Dictionary<Vector2Int, Chess>();
    public List<Chess> chessList = new();

    private void OnEnable()
    {
        EventCenter.GetInstance().AddEventListener<Vector2Int>("DisCardChess",DestroyChess);
    }

    private void OnDisable()
    {
        EventCenter.GetInstance().RemoveEventListener<Vector2Int>("DisCardChess",DestroyChess);
    }

    // ReSharper disable Unity.PerformanceAnalysis
    public void InitChess(BaseChessDateSo date, Vector2Int position ,ChessSide side)
    {
        var go = PoolTool.GetInstance().GetObjectFromPool(nameof(Chess));
        var vector3 = Vector2ToVector3(position);
        go.transform.position = vector3;
        Chess c = go.GetComponent<Chess>();
        c.InitChess(date,position,side);
        chessDict.Add(position, c);
        chessList.Add(c);
        ChessBoardMgr.GetInstance().SetChessDate(date, c,position);
        foreach (var skillConfig in date.skill)
        {
            skillConfig.Init(c);
        }   
        
        EventCenter.GetInstance().EventTrigger<GameEvent>(SkillEventName.EventChangeChess.ToString(),new ChangeEvent(c));
        
        EventCenter.GetInstance().EventTrigger<GameEvent>(SkillEventName.EventPlacedChess.ToString(),new PlacedEvent(c));
    }
    

    private Vector3 Vector2ToVector3(Vector2Int vector2)
    {
        return  new Vector3(vector2.x - 3.5f, vector2.y - 3.5f, 0);
    }

    private void DestroyChess(Vector2Int position)
    {
        StartCoroutine(ReallyDestroyChess(position));
    }

    private IEnumerator ReallyDestroyChess(Vector2Int position)
    {
        yield return 2;
        // 将牌释放回对象池
        if (chessDict.ContainsKey(position))
        {
            foreach (var skillConfig in chessDict[position].chessDate.skill)
            {
                skillConfig.Remove(chessDict[position]);
            }
            PoolTool.GetInstance().ReleaseObjectToPool(nameof(Chess), chessDict[position].gameObject);
            chessList.Remove(chessDict[position]);
            chessDict.Remove(position);
        }
            
    }

    public bool MoveChess(Vector2Int originPosition, Vector2Int targetPosition,Vector2Int attackPosition = default)
    {
        var side = chessDict[originPosition].GetChessSide();
        chessDict.Add(targetPosition, chessDict[originPosition]);
        ChessBoardMgr.GetInstance().MoveChess(originPosition,targetPosition);
        chessDict[originPosition].ChessDetail.Position = targetPosition;
        chessDict[originPosition].transform.DOMove(Vector2ToVector3(targetPosition), moveDuration).OnComplete(() =>
        {
            if (attackPosition != default)
            {
                Damage(targetPosition, attackPosition);
            }
        });
        chessDict.Remove(originPosition);
        if (side == ChessSide.Player1 && targetPosition.y == 7)
        {
            StartCoroutine(DeductCharacterHp(side, targetPosition));
            return true;
        }
        else if (side == ChessSide.Player2 && targetPosition.y == 0)
        {
            StartCoroutine(DeductCharacterHp(side, targetPosition));
            return true;
        }
        return false;
    }
    

    private IEnumerator DeductCharacterHp(ChessSide side , Vector2Int targetPosition)
    {
        yield return new WaitForSeconds(1);
        var temp = chessDict[targetPosition].ChessDetail.Attack;
        DestroyChess(targetPosition);
        ChessBoardMgr.GetInstance().DisCardChess(targetPosition);
        EventCenter.GetInstance().EventTrigger("DeductCharacterHp", side, temp);
        


    }

    public void GameOver()
    {
        foreach (var pair in chessDict)
        {
            if (chessDict.ContainsKey(pair.Key))
                foreach (var skillConfig in pair.Value.chessDate.skill)
                {
                    skillConfig.Remove(pair.Value);
                }
            PoolTool.GetInstance().ReleaseObjectToPool(nameof(Chess), pair.Value.gameObject);
        }
        chessList.Clear();
        chessDict.Clear();
    }





    private Vector3 originalPosition; // 棋子A的原始位置
    private bool isAttacking = false; // 是否正在攻击
    private bool isReturning = false; // 是否正在返回
    private readonly float moveDuration = 0.2f; // 移动动画持续时间
    private readonly float returnDuration = 0.1f; // 返回动画持续时间

    public void Damage(Vector2Int originPosition, Vector2Int targetPosition)
    {
        if (!isAttacking && !isReturning)
        {
            isAttacking = true; // 开始攻击
            originalPosition = Vector2ToVector3(originPosition);
            MoveToAttackPosition(originPosition,targetPosition); // 移动到攻击位置
        }
        
        print("造成了"+chessDict[originPosition].ChessDetail.Attack+"点伤害");
    }

    private void MoveToAttackPosition(Vector2Int originPosition, Vector2Int targetPosition)
    {
        // 计算攻击位置：棋子B旁边
        Vector3 attackPosition = chessDict[targetPosition].transform.position;

        // 使用 DOTween 移动棋子A到攻击位置
        chessDict[originPosition].transform.DOMove(attackPosition, moveDuration).SetEase(Ease.Linear).SetDelay(0.1f).OnComplete(() =>
        {
            // 到达攻击位置后执行攻击逻辑
            bool isDead = chessDict[targetPosition].BeAttack(chessDict[originPosition].ChessDetail.Attack,chessDict[originPosition]);
            isAttacking = false;
            isReturning = true; // 开始返回
            if (isDead)
            {
                
            }
            else
            {
                ShowHitEffect(targetPosition);
            }
            MoveToOriginalPosition(originPosition); // 返回原始位置
        });
    }
    
    private void MoveToOriginalPosition(Vector2Int originPosition)
    {
        // 使用 DOTween 移动棋子A返回原始位置
        chessDict[originPosition].transform.DOMove(originalPosition, returnDuration).SetEase(Ease.Linear).OnComplete(() =>
        {
            isReturning = false; // 返回完成
        });
    }
    
    private void ShowHitEffect(Vector2Int target)
    {
        // 在这里添加棋子B被撞击的视觉效果
        // 例如：粒子效果、动画、音效等

        // 可以使用 DOTween 的震动效果
        chessDict[target].transform.DOShakePosition(0.2f, new Vector3(0.1f, 0.1f, 0), 10, 0.1f, false, true);
    }


    public Chess GetChessByName(string chessName)
    {
        foreach (var chess in chessList)
        {
            if (chess.chessDate.chessName == chessName)
            {
                return chess;
            }
        }
        return null;
    }
    
    public List<Chess> GetAllChessByName(string chessName)
    {
        var list = new List<Chess>();
        foreach (var chess in chessList)
        {
            if (chess.chessDate.chessName == chessName)
            {
                list.Add(chess);
            }
        }
        return list;
    }

    
}
